package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.redisconfig.RedissonAutoConfiguration;
import com.mall.commons.tool.utils.NumberUtils;
import com.mall.order.biz.callback.SendEmailCallback;
import com.mall.order.biz.callback.TransCallback;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.utils.GlobalIdGeneratorUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:01
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * 插入order表与orderItem表
     * @param context
     * @return
     */
    @SneakyThrows
    @Override
    public boolean handle(TransHandlerContext context) {


        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        //插入订单表
        Order order = new Order();
        //发号器 TODO
        String orderId = UUID.randomUUID().toString();
        //String newOrderId = orderId.replace("-", "");
        order.setOrderId(orderId);
        order.setUserId(createOrderContext.getUserId());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setBuyerNick(createOrderContext.getBuyerNickName());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);

        int orderAffectedRows = orderMapper.insert(order);
        if (orderAffectedRows < 1) {
            throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),"订单信息保存数据库失败");
        }

        //插入订单商品关联表
        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto dto : dtoList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setId(UUID.randomUUID().toString());
            orderItem.setOrderId(orderId);
            orderItem.setItemId(dto.getProductId());
            orderItem.setPicPath(dto.getProductImg());
            Long productNum = dto.getProductNum();
            orderItem.setNum(productNum.intValue());
            orderItem.setTitle(dto.getProductName());
            BigDecimal salePrice = dto.getSalePrice();
            orderItem.setPrice(salePrice.doubleValue());
            BigDecimal totalFee = salePrice.multiply(new BigDecimal(productNum));
            orderItem.setTotalFee(totalFee.doubleValue());
            //已锁定库存
            orderItem.setStatus(1);
            int affectedRows = orderItemMapper.insert(orderItem);
            if (affectedRows < 1) {
                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),"订单商品关联信息保存数据库失败");
            }
        }
        createOrderContext.setOrderId(orderId);

        return true;
    }
}
